<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <canvas id="c1" width="600" height="400"></canvas>

    <script>
        /** @type {HTMLCanvasElement} */
        // 画布
        let c1 = document.getElementById("c1")
        // 画笔
        let ctx = c1.getContext("2d")

        // 封装heart类
        class Heart {
            constructor(x, y) {
                // 坐标
                this.x = x
                this.y = y
                this.color = "red"
                // 监听鼠标位置
                c1.onmousemove = (e) => {
                    let x = e.offsetX
                    let y = e.offsetY
                    // // 判断鼠标当前点是否在heartPath路径上
                    let isInPath = ctx.isPointInPath(this.heartPath, x, y)

                    ctx.clearRect(0, 0, c1.width, c1.height)
                    if (isInPath) {
                        this.color = "blue"
                    } else {
                        this.color = "red"
                    }
                    this.draw()
                }
            }
            // 修改位置
            setPosition(x, y) {
                this.x = x
                this.y = y
            }
            // 画出爱心并设置阴影
            draw() {
                // 设置爱心路径
                this.heartPath = new Path2D()
                this.heartPath.moveTo(this.x, this.y)
                this.heartPath.bezierCurveTo(this.x + 50, this.y - 50, this.x + 100, this.y, this.x, this.y + 50)
                this.heartPath.bezierCurveTo(this.x - 100, this.y, this.x - 50, this.y - 50, this.x, this.y)

                // 修改画笔状态前先保存，最后还原
                ctx.save()

                ctx.fillStyle = this.color
                ctx.shadowOffsetX = 10
                ctx.shadowOffsetY = 10
                ctx.shadowBlur = 5
                ctx.shadowColor = "#ccc"
                ctx.fill(this.heartPath)

                ctx.restore()
            }
        }

        let heart = new Heart(100, 100)
        heart.draw()
    </script>
</body>

</html>